package com.example.artemis.service;

import com.example.artemis.config.QueueConsumerConfig;
import com.example.artemis.factory.QueueMessageConsumerFactory;
import com.example.artemis.interfaces.MessageConsumer;
import com.example.artemis.statistics.StatisticsService;
import com.example.artemis.statistics.DefaultStatisticsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CompletableFuture;

/**
 * 重构后的消息消费者服务
 * 使用工厂模式创建消费者实例，简化服务逻辑
 * 统计功能已解耦到独立的统计服务中
 */
public class MessageConsumerService {

    private static final Logger logger = LoggerFactory.getLogger(MessageConsumerService.class);

    private final MessageConsumer messageConsumer;
    private final StatisticsService statisticsService;
    private volatile boolean running = false;

    public MessageConsumerService() {
        this(new DefaultStatisticsService());
    }

    public MessageConsumerService(StatisticsService statisticsService) {
        // 创建配置
        QueueConsumerConfig config = new QueueConsumerConfig();

        // 创建工厂
        QueueMessageConsumerFactory factory = new QueueMessageConsumerFactory();

        // 创建消费者实例
        this.messageConsumer = factory.createConsumer(config);
        this.statisticsService = statisticsService;

        // 不在这里启动统计服务，由外部统一管理
        logger.debug("MessageConsumerService 初始化完成，使用外部统计服务");
    }

    /**
     * 启动消费者服务
     */
    public CompletableFuture<ConsumptionResult> startConsumers() {
        logger.info("启动消息消费者服务");
        running = true;

        return CompletableFuture.runAsync(() -> {
            try {
                messageConsumer.start();
            } catch (Exception e) {
                logger.error("消费者启动失败", e);
                throw new RuntimeException("消费者启动失败", e);
            }
        }).thenApply(v -> {
            // 现在统计由统计服务管理，这里返回基本的结果信息
            return new ConsumptionResult(0, 0); // 实际数据由统计服务提供
        });
    }

    /**
     * 停止消费者服务
     */
    public void stop() {
        logger.info("停止消息消费者服务");
        running = false;

        if (messageConsumer != null) {
            messageConsumer.stop();
        }

        // 不在这里停止统计服务，由外部统一管理
        logger.info("消息消费者服务已停止");
    }

    /**
     * 获取消费统计信息
     */
    public ConsumptionStats getStats() {
        if (statisticsService != null) {
            var globalStats = statisticsService.getGlobalStatistics();
            return new ConsumptionStats(
                globalStats.getTotalProcessed(),
                globalStats.getTotalFailed(),
                globalStats.getTotalRetried(),
                globalStats.getAverageProcessingTime()
            );
        }
        return new ConsumptionStats(0, 0, 0, 0);
    }

    /**
     * 获取统计服务实例
     */
    public StatisticsService getStatisticsService() {
        return statisticsService;
    }

    /**
     * 检查服务是否正在运行
     */
    public boolean isRunning() {
        return running && (messageConsumer != null && messageConsumer.isRunning());
    }

    // ================== 数据类定义 ==================

    /**
     * 消费结果
     */
    public record ConsumptionResult(long successfulConsumptions, long failedConsumptions) {}

    /**
     * 消费统计信息
     */
    public record ConsumptionStats(
        long totalProcessed,
        long totalFailed,
        long totalRetried,
        double averageProcessingTime
    ) {}
}